Skip to content

Exercises

Interval counter

In the sandbox below, we want to count how many seconds have elapsed since the component mounted:

Unfortunately, our attempted solution appears to have a bug: it stops counting at 1. 🤔

Your mission is to fix the bug, so that the number keeps incrementing past 1.

Acceptance Criteria:

  • The UI should accurately show the # of seconds since mount.
  • There should be no lint warnings, and no eslint-disable comments.

Code Playground

import React from 'react';

function Timer() {
const [count, setCount] = React.useState(0);

React.useEffect(() => {
const intervalId = window.setInterval(() => {
setCount(count + 1);
}, 1000);

return () => {
window.clearInterval(intervalId);
};
// eslint-disable-next-line
}, []);

return (
<div className="timer">
<h1>Seconds since load:</h1>
<p>{count}</p>
</div>
);
}

export default Timer;

Solution: